let querystring = require('querystring');
let https = require('https');
let request = require('request');
let { appid, appSecret } = require('../config');


const getPreInfoByCode = code => {
  return new Promise( (resolve, reject ) => {
    let url = 'https://api.weixin.qq.com/sns/oauth2/access_token?';

    let queryStr = querystring.stringify({
      appid: appid,
      secret: appSecret,
      code: code,
      grant_type: 'authorization_code'
    });



    request( {
      url: url + queryStr,
      // json: true
    } ,  (error, response, body) => {
      // console.log('error:', error);
      // console.log('statusCode:', response && response.statusCode);
      // console.log('body:', body);
      if (error){
        reject( response && response.statusCode + ': ' + error);
      } else {
        let { openid, access_token } = JSON.parse(body);


        if (openid){
          resolve( { openid, access_token } )
        } else {
          reject( '无法根据code来获取有效的openid' )
        }
      }

    });
  } );
};


const getPreInfo = code => {
  if ( !code ) throw Error( 'need code before get user openId ' );

  return getPreInfoByCode( code )
};

module.exports = getPreInfo;


